import constants
import time
import base64
import hashlib
import os.path
import string

def strip_uri_root(uri):
    if uri.find('//') != -1:
        return uri[uri.find('/', uri.find('//')+2):]
    else:
        return uri


def digest(data):
    return len(data) > constants.DigestLength and data[:constants.DigestLength] + '...' or data

# taken from App.Common

weekday_abbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
weekday_full = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
                'Friday', 'Saturday', 'Sunday']
monthname    = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

def rfc1123_date(ts=None):
    # Return an RFC 1123 format date string, required for
    # use in HTTP Date headers per the HTTP 1.1 spec.
    # 'Fri, 10 Nov 2000 16:21:09 GMT'
    if ts is None: ts=time.time()
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(ts)
    return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (weekday_abbr[wd],
                                                    day, monthname[month],
                                                    year,
                                                    hh, mm, ss)
def iso8601_date(ts=None):
    # Return an ISO 8601 formatted date string, required
    # for certain DAV properties.
    # '2000-11-10T16:21:09-08:00
    if ts is None: ts=time.time()
    return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(ts))

def rfc850_date(ts=None):
    # Return an HTTP-date formatted date string.
    # 'Friday, 10-Nov-00 16:21:09 GMT'
    if ts is None: ts=time.time()
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(ts)
    return "%s, %02d-%3s-%2s %02d:%02d:%02d GMT" % (
            weekday_full[wd],
            day, monthname[month],
            str(year)[2:],
            hh, mm, ss)

def separate_ns_ln(tag):
    """
    Separate the XML tag into (namespace, localname)
    """
    idx = tag.find('}')
    ns = ln = ''
    if idx != -1:
        ns = tag[1:idx]
        ln = tag[idx+1:]
    else:
        ln = tag
    return (ns, ln)

def read_chunked(data, length=0):
    if hasattr(data, 'read'):
        while length > 0:
            if length >= constants.BUFFER_SIZE:
                buf = data.read(constants.BUFFER_SIZE)
                length -= constants.BUFFER_SIZE
            else:
                buf = data.read(length)
                length = 0
            # print('Got chunk: %s' % digest(buf))
            yield buf
    elif hasattr(data, '__iter__'):
        for iter in data:
            if iter:
                yield iter
    elif isinstance(data, (str, unicode)):
        yield data
    else:
        raise TypeError

def keyShorten(key):
    return base64.b16encode(hashlib.md5(key).digest())

def basename(url):
    print('Basename(%s)' % url)
    if url.endswith('/'):
        return os.path.basename(url[:-1])
    else:
        return os.path.basename(url)

def parent(uri):
    if uri == '/':
        return '/'
    elif uri.endswith('/'):
        return uri[0:uri[:len(uri) - 1].rfind('/') + 1]
    else:
        return uri[0:uri.rfind('/') + 1]

    
def property2variable(name):
    if name == 'self':
        name = '_self'
    return name.replace('-', '_')

def gen_name(uri, data):
    return base64.b16encode(hashlib.md5(uri + data).digest())
